﻿-- 金币
local math_mod = math.fmod or math.mod

local Icon_Width = 13
local Icon_Height = 13

local diminfo_Gold = CreateFrame("Button", "diminfo_Gold", UIParent)

local GoldText = diminfo_Gold:CreateFontString("Text", "OVERLAY")
GoldText:SetFont(STANDARD_TEXT_FONT, 14, "OUTLINE")
GoldText:SetPoint("LEFT", diminfo_Bag, "RIGHT", 30, 0)
diminfo_Gold:SetPoint("LEFT", diminfo_Bag, "RIGHT", 30, 0)

local Gold = diminfo_Gold:CreateTexture(nil, "OVERLAY")
Gold:SetTexture("Interface\\MoneyFrame\\UI-MoneyIcons")
SetSize(Gold, Icon_Width, Icon_Height)
Gold:SetPoint("LEFT", GoldText, "RIGHT", 0, 0)
Gold:SetTexCoord(0, 0.255, 0, 1)

local SilverText = diminfo_Gold:CreateFontString("Text", "OVERLAY")
SilverText:SetFont(STANDARD_TEXT_FONT, 14, "OUTLINE")
SilverText:SetPoint("LEFT", Gold, "RIGHT", 0, 0)
diminfo_Gold:SetPoint("LEFT", Gold, "RIGHT", 0, 0)

local Silver = diminfo_Gold:CreateTexture(nil, "OVERLAY")
Silver:SetTexture("Interface\\MoneyFrame\\UI-MoneyIcons")
SetSize(Silver, Icon_Width, Icon_Height)
Silver:SetPoint("LEFT", SilverText, "RIGHT", 0, 0)
Silver:SetTexCoord(0.256, 0.511, 0, 1)

local function ShowMoneys()
	local gold = floor(GetMoney() / (COPPER_PER_SILVER * SILVER_PER_GOLD))
	local silver = math_mod(floor(GetMoney() / (COPPER_PER_SILVER)), 100)

	GoldText:SetText(Over1E3toK(gold))
	SilverText:SetText(silver)
	SetSize(diminfo_Gold, GoldText:GetStringWidth() + SilverText:GetStringWidth()
		    + Icon_Width * 2, Icon_Height)
end

local function OnEvent()
	-- 记录收入与支出
	if event == "PLAYER_LOGIN" then
		diminfo_lastmoney = GetMoney()
		diminfo_income = 0
		ShowMoneys()
	elseif event == "PLAYER_MONEY" then
		local diminfo_newmoney = GetMoney()
		if diminfo_newmoney ~= diminfo_lastmoney then
			local inc_dec = (diminfo_newmoney - diminfo_lastmoney)
			diminfo_income = diminfo_income + inc_dec
			diminfo_lastmoney = diminfo_newmoney
		end
		ShowMoneys()
	end
end

diminfo_Gold:SetScript("OnEnter", function()
	GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT")
	GameTooltip:ClearLines()
	GameTooltip:AddLine("金币")
	GameTooltip:AddLine("左键:背包", .3, 1, .6)
	if IsAddOnLoaded("Accountant") then
		GameTooltip:AddLine("右键:收支明细", .3, 1, .6)
	end
	if diminfo_income > 0 then
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine("本次登录净利润")
		SetTooltipMoney(GameTooltip, diminfo_income)
	end
	GameTooltip:Show()
end)
diminfo_Gold:SetScript("OnLeave", function() GameTooltip:Hide() end)

diminfo_Gold:RegisterEvent("PLAYER_LOGIN")
diminfo_Gold:RegisterEvent("PLAYER_MONEY")
diminfo_Gold:SetScript("OnEvent", OnEvent)
diminfo_Gold:SetScript("OnMouseDown", function()
	if arg1 == "LeftButton" then
		OpenAllBags()
	else
		if IsAddOnLoaded("Accountant") then
			AccountantButton_OnClick()
		end
	end
end)